import 'package:flutter/foundation.dart';
import '../models/mood_record.dart';
import '../models/mood_type.dart';
import '../models/mood_statistics.dart';
import '../services/mood_repository.dart';
import '../services/data_seeder.dart';

/// 情绪记录状态管理Provider
/// 管理应用中所有与情绪记录相关的状态和操作
class MoodProvider with ChangeNotifier {
  final MoodRepository _repository = MoodRepository();
  late final DataSeeder _dataSeeder;

  // 状态变量
  List<MoodRecord> _allRecords = [];
  List<MoodRecord> _todayRecords = [];
  MoodRecord? _latestRecord;
  MoodStatistics? _weeklyStats;
  MoodStatistics? _monthlyStats;
  
  // 加载状态
  bool _isLoading = false;
  bool _isInitialized = false;
  String? _error;
  
  // 筛选和搜索状态
  String _searchKeyword = '';
  MoodType? _selectedMoodFilter;
  DateTime? _startDateFilter;
  DateTime? _endDateFilter;
  List<MoodRecord> _filteredRecords = [];

  /// 构造函数
  MoodProvider() {
    _dataSeeder = DataSeeder(_repository);
  }

  /// 公共初始化方法
  Future<void> initialize() async {
    await _initialize();
  }

  // Getters
  /// 获取所有记录
  List<MoodRecord> get allRecords => List.unmodifiable(_allRecords);
  
  /// 获取所有记录（别名，用于兼容性）
  List<MoodRecord> get records => allRecords;
  List<MoodRecord> get todayRecords => _todayRecords;
  MoodRecord? get latestRecord => _latestRecord;
  MoodStatistics? get weeklyStats => _weeklyStats;
  MoodStatistics? get monthlyStats => _monthlyStats;
  bool get isLoading => _isLoading;
  bool get isInitialized => _isInitialized;
  String? get error => _error;
  String get searchKeyword => _searchKeyword;
  MoodType? get selectedMoodFilter => _selectedMoodFilter;
  DateTime? get startDateFilter => _startDateFilter;
  DateTime? get endDateFilter => _endDateFilter;
  List<MoodRecord> get filteredRecords => _filteredRecords;
  
  /// 是否有今日记录
  bool get hasTodayRecord => _todayRecords.isNotEmpty;
  
  /// 记录总数
  int get totalRecordsCount => _allRecords.length;
  
  /// 是否有任何记录
  bool get hasAnyRecords => _allRecords.isNotEmpty;

  /// 初始化Provider
  Future<void> _initialize() async {
    await _setLoading(true);
    try {
      // 检查是否需要生成示例数据
      if (await _dataSeeder.shouldSeedData()) {
        await _dataSeeder.seedData();
      }
      
      // 加载所有数据
      await _loadAllData();
      _isInitialized = true;
      _clearError();
    } catch (e) {
      _setError('初始化失败: $e');
    } finally {
      await _setLoading(false);
    }
  }

  /// 加载所有数据
  Future<void> _loadAllData() async {
    await Future.wait([
      loadAllRecords(),
      loadTodayRecords(),
      loadLatestRecord(),
      loadWeeklyStatistics(),
      loadMonthlyStatistics(),
    ]);
  }

  /// 加载所有记录
  Future<void> loadAllRecords() async {
    try {
      _allRecords = await _repository.getAllMoodRecords();
      _applyFilters();
      notifyListeners();
    } catch (e) {
      _setError('加载记录失败: $e');
    }
  }

  /// 加载今日记录
  Future<void> loadTodayRecords() async {
    try {
      _todayRecords = await _repository.getTodayMoodRecords();
      notifyListeners();
    } catch (e) {
      _setError('加载今日记录失败: $e');
    }
  }

  /// 加载最新记录
  Future<void> loadLatestRecord() async {
    try {
      final latestRecords = await _repository.getLatestMoodRecords(count: 1);
      _latestRecord = latestRecords.isNotEmpty ? latestRecords.first : null;
      notifyListeners();
    } catch (e) {
      _setError('加载最新记录失败: $e');
    }
  }

  /// 加载周统计数据
  Future<void> loadWeeklyStatistics() async {
    try {
      _weeklyStats = await _repository.getRecentWeekStatistics();
      notifyListeners();
    } catch (e) {
      _setError('加载周统计数据失败: $e');
    }
  }

  /// 加载月统计数据
  Future<void> loadMonthlyStatistics() async {
    try {
      _monthlyStats = await _repository.getRecentMonthStatistics();
      notifyListeners();
    } catch (e) {
      _setError('加载月统计数据失败: $e');
    }
  }

  /// 添加新的情绪记录
  /// [record] 要添加的情绪记录
  /// 返回保存后的记录
  Future<MoodRecord?> addMoodRecord(MoodRecord record) async {
    await _setLoading(true);
    try {
      final savedRecord = await _repository.saveMoodRecord(record);
      
      // 更新本地状态
      _allRecords.insert(0, savedRecord);
      if (savedRecord.isToday) {
        _todayRecords.insert(0, savedRecord);
      }
      _latestRecord = savedRecord;
      
      // 重新加载统计数据
      await Future.wait([
        loadWeeklyStatistics(),
        loadMonthlyStatistics(),
      ]);
      
      _applyFilters();
      _clearError();
      notifyListeners();
      return savedRecord;
    } catch (e) {
      _setError('保存记录失败: $e');
      return null;
    } finally {
      await _setLoading(false);
    }
  }

  /// 更新情绪记录
  /// [record] 要更新的情绪记录
  /// 返回更新后的记录
  Future<MoodRecord?> updateMoodRecord(MoodRecord record) async {
    await _setLoading(true);
    try {
      final updatedRecord = await _repository.updateMoodRecord(record);
      
      // 更新本地状态
      final index = _allRecords.indexWhere((r) => r.id == record.id);
      if (index != -1) {
        _allRecords[index] = updatedRecord;
      }
      
      final todayIndex = _todayRecords.indexWhere((r) => r.id == record.id);
      if (todayIndex != -1) {
        _todayRecords[todayIndex] = updatedRecord;
      }
      
      if (_latestRecord?.id == record.id) {
        _latestRecord = updatedRecord;
      }
      
      // 重新加载统计数据
      await Future.wait([
        loadWeeklyStatistics(),
        loadMonthlyStatistics(),
      ]);
      
      _applyFilters();
      _clearError();
      notifyListeners();
      return updatedRecord;
    } catch (e) {
      _setError('更新记录失败: $e');
      return null;
    } finally {
      await _setLoading(false);
    }
  }

  /// 删除情绪记录
  /// [id] 要删除的记录ID
  /// 返回是否删除成功
  Future<bool> deleteMoodRecord(int id) async {
    await _setLoading(true);
    try {
      await _repository.deleteMoodRecord(id);
      
      // 更新本地状态
      _allRecords.removeWhere((r) => r.id == id);
      _todayRecords.removeWhere((r) => r.id == id);
      
      if (_latestRecord?.id == id) {
        await loadLatestRecord();
      }
      
      // 重新加载统计数据
      await Future.wait([
        loadWeeklyStatistics(),
        loadMonthlyStatistics(),
      ]);
      
      _applyFilters();
      _clearError();
      notifyListeners();
      return true;
    } catch (e) {
      _setError('删除记录失败: $e');
      return false;
    } finally {
      await _setLoading(false);
    }
  }

  /// 搜索记录
  /// [keyword] 搜索关键词
  Future<void> searchRecords(String keyword) async {
    _searchKeyword = keyword.trim();
    _applyFilters();
    notifyListeners();
  }

  /// 设置情绪类型筛选
  /// [moodType] 要筛选的情绪类型，null表示清除筛选
  void setMoodFilter(MoodType? moodType) {
    _selectedMoodFilter = moodType;
    _applyFilters();
    notifyListeners();
  }

  /// 设置日期范围筛选
  /// [startDate] 开始日期
  /// [endDate] 结束日期
  void setDateRangeFilter(DateTime? startDate, DateTime? endDate) {
    _startDateFilter = startDate;
    _endDateFilter = endDate;
    _applyFilters();
    notifyListeners();
  }

  /// 清除所有筛选条件
  void clearFilters() {
    _searchKeyword = '';
    _selectedMoodFilter = null;
    _startDateFilter = null;
    _endDateFilter = null;
    _applyFilters();
    notifyListeners();
  }

  /// 应用筛选条件
  void _applyFilters() {
    List<MoodRecord> filtered = List.from(_allRecords);
    
    // 应用搜索关键词筛选
    if (_searchKeyword.isNotEmpty) {
      filtered = filtered.where((record) {
        final content = record.diaryContent?.toLowerCase() ?? '';
        final tags = record.tags.join(' ').toLowerCase();
        final keyword = _searchKeyword.toLowerCase();
        return content.contains(keyword) || tags.contains(keyword);
      }).toList();
    }
    
    // 应用情绪类型筛选
    if (_selectedMoodFilter != null) {
      filtered = filtered.where((record) => record.moodType == _selectedMoodFilter).toList();
    }
    
    // 应用日期范围筛选
    if (_startDateFilter != null && _endDateFilter != null) {
      filtered = filtered.where((record) {
        final recordDate = record.createdAt;
        return recordDate.isAfter(_startDateFilter!) && 
               recordDate.isBefore(_endDateFilter!.add(const Duration(days: 1)));
      }).toList();
    }
    
    _filteredRecords = filtered;
  }

  /// 获取指定日期范围的统计数据
  /// [startDate] 开始日期
  /// [endDate] 结束日期
  /// 返回统计数据
  Future<MoodStatistics?> getCustomStatistics(
    DateTime startDate,
    DateTime endDate,
  ) async {
    try {
      return await _repository.getMoodStatistics(startDate, endDate);
    } catch (e) {
      _setError('获取统计数据失败: $e');
      return null;
    }
  }

  /// 刷新所有数据
  Future<void> refresh() async {
    await _setLoading(true);
    try {
      await _loadAllData();
      _clearError();
    } catch (e) {
      _setError('刷新数据失败: $e');
    } finally {
      await _setLoading(false);
    }
  }

  /// 重新生成示例数据（用于测试）
  Future<void> regenerateData() async {
    await _setLoading(true);
    try {
      await _repository.clearDatabase();
      await _dataSeeder.seedData();
      await _loadAllData();
      _clearError();
    } catch (e) {
      _setError('重新生成数据失败: $e');
    } finally {
      await _setLoading(false);
    }
  }

  /// 设置加载状态
  Future<void> _setLoading(bool loading) async {
    if (_isLoading != loading) {
      _isLoading = loading;
      notifyListeners();
      // 给UI一点时间更新
      await Future.delayed(const Duration(milliseconds: 50));
    }
  }

  /// 设置错误信息
  void _setError(String error) {
    _error = error;
    if (kDebugMode) {
      print('MoodProvider Error: $error');
    }
    notifyListeners();
  }

  /// 清除错误信息
  void _clearError() {
    if (_error != null) {
      _error = null;
      notifyListeners();
    }
  }

  /// 清除错误（供UI调用）
  void clearError() {
    _clearError();
  }

  /// 获取情绪类型分布数据（用于饼图）
  Map<MoodType, int> getMoodTypeDistribution() {
    final distribution = <MoodType, int>{};
    for (final record in _allRecords) {
      distribution[record.moodType] = (distribution[record.moodType] ?? 0) + 1;
    }
    return distribution;
  }

  /// 获取最近N天的情绪趋势数据（用于折线图）
  /// [days] 天数
  /// 返回日期和平均情绪评分的映射
  Map<DateTime, double> getRecentMoodTrend(int days) {
    final now = DateTime.now();
    final startDate = now.subtract(Duration(days: days));
    
    final trendData = <DateTime, List<int>>{};
    
    // 收集每天的情绪评分
    for (final record in _allRecords) {
      if (record.createdAt.isAfter(startDate)) {
        final date = DateTime(
          record.createdAt.year,
          record.createdAt.month,
          record.createdAt.day,
        );
        
        trendData[date] ??= [];
        trendData[date]!.add(record.moodScore.round());
      }
    }
    
    // 计算每天的平均评分
    final averageData = <DateTime, double>{};
    for (final entry in trendData.entries) {
      final average = entry.value.reduce((a, b) => a + b) / entry.value.length.toDouble();
      averageData[entry.key] = average;
    }
    
    return averageData;
  }

  /// 获取标签使用频率（用于词云）
  Map<String, int> getTagFrequency() {
    final frequency = <String, int>{};
    for (final record in _allRecords) {
      for (final tag in record.tags) {
        frequency[tag] = (frequency[tag] ?? 0) + 1;
      }
    }
    return frequency;
  }

  /// 更新情绪记录
  /// [record] 要更新的记录
  Future<void> updateRecord(MoodRecord record) async {
    try {
      await _repository.updateMoodRecord(record);
      await _loadAllData();
      _clearError();
    } catch (e) {
      _setError('更新记录失败: $e');
      rethrow;
    }
  }

  /// 删除情绪记录
  /// [recordId] 要删除的记录ID
  Future<void> deleteRecord(String recordId) async {
    try {
      final id = int.tryParse(recordId);
      if (id == null) {
        throw Exception('无效的记录ID');
      }
      await _repository.deleteMoodRecord(id);
      await _loadAllData();
      _clearError();
    } catch (e) {
      _setError('删除记录失败: $e');
      rethrow;
    }
  }

  /// 清除所有记录
  Future<void> clearAllRecords() async {
    try {
      await _repository.clearAllRecords();
      await _loadAllData();
      _clearError();
    } catch (e) {
      _setError('清除记录失败: $e');
      rethrow;
    }
  }

  /// 根据ID获取记录
  /// [recordId] 记录ID
  Future<MoodRecord?> getRecordById(String recordId) async {
    try {
      return await _repository.getRecordById(recordId);
    } catch (e) {
      _setError('获取记录失败: $e');
      return null;
    }
  }

  @override
  void dispose() {
    _repository.close();
    super.dispose();
  }
}